package com.zhiyou100.aspect;

import java.lang.reflect.Method;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhiyou100.mapper.LogMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zhiyou100.annotation.Auth;
import com.zhiyou100.model.Log;
import com.zhiyou100.model.User;
@Component
@Aspect
public class SetChar{

	@Autowired
	private LogMapper mapper;
	
	
	@Pointcut("@annotation(com.zhiyou100.annotation.Auth)")
	public void auth() {}
	
//	@Before("@annotation(com.zhiyou100.annotation.Auth)")
	@Before("auth()")
	public void preHandle(JoinPoint join) throws Throwable{
		Log log = new Log();
		HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		HttpServletResponse resp = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
		String ip = req.getRemoteAddr();
		log.setIp(ip);
		System.out.println("日志 - ip : " + ip);
		String methodName = join.getSignature().getName();
		log.setMethod(methodName);
		System.out.println("日志 - methodName : " + methodName);
		Method[] methods = join.getTarget().getClass().getMethods();
		for(Method method : methods) {
			if(method.getName().equals(methodName)) {
				String value = method.getAnnotation(Auth.class).value();
				log.setDesc(value);
				System.out.println("日志 - 描述 :" + value);
			}
		}
		log.setDate(new Timestamp(System.currentTimeMillis()));
		try{
			mapper.insert(log);
		}catch (Exception e){
			e.printStackTrace();
		}
	}

}
